<!-- src/views/system/UserPasswordReset.vue -->
<script setup>
import { ref, reactive } from 'vue'
import { useUserStore } from '@/stores/userStore.js'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const dialogVisible = ref(false)
const loading = ref(false)
const userId = ref(null)

const passwordForm = reactive({
  password: ''
})

const passwordRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ]
}

const passwordFormRef = ref(null)

const open = (id) => {
  userId.value = id
  dialogVisible.value = true
  passwordForm.password = ''
}

const submitForm = () => {
  passwordFormRef.value?.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const data = {
          userId: userId.value,
          password: passwordForm.password
        }
        await userStore.resetUserPassword(data)
        ElMessage.success('密码重置成功')
        dialogVisible.value = false
      } catch (error) {
        ElMessage.error('密码重置失败: ' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }
  })
}

defineExpose({
  open
})
</script>

<template>
  <el-dialog
      title="重置密码"
      v-model="dialogVisible"
      width="400px"
      :close-on-click-modal="false"
  >
    <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
        label-width="80px"
    >
      <el-form-item label="新密码" prop="password">
        <el-input
            v-model="passwordForm.password"
            type="password"
            placeholder="请输入新密码"
            show-password
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button
          type="primary"
          @click="submitForm"
          :loading="loading"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
</template>
